﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text;
using XinYiOffice.Common;
using System.Collections.Generic;
using XinYiOffice.Web.UI;
using XinYiOffice.Basic;

namespace XinYiOffice.Web.Sys.Roles
{
    public partial class Modify : BasicPage
    {
        public int lay = 0;

        public DataSet rpList;
        public DataTable dtrpList;
        public DataTable dtPermissionsList;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                if (Request.Params["id"] != null && Request.Params["id"].Trim() != "")
                {
                    int Id = (Convert.ToInt32(Request.Params["id"]));
                    ShowInfo(Id);
                }
            }
        }

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            BindData();
        }

        protected void BindData()
        {
            GetMenuTree(0, ref tbody_cell);
        }

        #region 菜单
        public void GetMenuTree(int pid, ref System.Web.UI.HtmlControls.HtmlGenericControl hgc)
        {
            DataRow[] dr = AppDataCacheServer.MenuTreeList().Select(string.Format("MenuTreeId={0}", pid));

            int CurrentId = 0;
            int CurrentParentMenuTreeId = 0;

            string _format = string.Empty;
            string _guid = string.Empty;

            foreach (DataRow _dr in dr)
            {
                lay++;//层级

                CurrentId = SafeConvert.ToInt(_dr["Id"], 0);
                CurrentParentMenuTreeId = SafeConvert.ToInt(_dr["MenuTreeId"], 0);
                _guid = SafeConvert.ToString(_dr["Guid"]);

                string name = SafeConvert.ToString(_dr["Name"]);
                bool isClass = GetClassInExist(CurrentId);

                System.Web.UI.HtmlControls.HtmlTableRow htr = new System.Web.UI.HtmlControls.HtmlTableRow();

                System.Web.UI.HtmlControls.HtmlTableCell htc_1 = new System.Web.UI.HtmlControls.HtmlTableCell();


                CheckBox cb = new CheckBox();
                cb.Text = name;
                //string strSign = "MENUTREE_" + CurrentId;
                string strSign = "MENUTREE_" + _guid;
                #region 初始化菜单权限
                DataSet dsSign = new BLL.Permissions().GetList(string.Format("Sign='{0}' and TenantId={1} ", strSign,CurrentTenantId));
                if (dsSign != null && dsSign.Tables[0].Rows.Count > 0)
                {
                    //cb.ToolTip = SafeConvert.ToString(dsSign.Tables[0].Rows[0]["Id"]);
                    cb.ToolTip = SafeConvert.ToString(dsSign.Tables[0].Rows[0]["Sign"]);
                }
                else
                {
                    Model.Permissions _per = new Model.Permissions();
                    _per.CreateAccountId = CurrentAccountId;
                    _per.CreateTime = DateTime.Now;
                    _per.Name = "菜单_" + name;
                    _per.PermissionCategoriesId = 0;
                    _per.Sign = strSign;
                    _per.TenantId = CurrentTenantId;

                    //cb.ToolTip = new BLL.Permissions().Add(_per).ToString();
                    new BLL.Permissions().Add(_per).ToString();
                    cb.ToolTip = strSign;
                }
                #endregion

                htc_1.Controls.Add(cb);


               
                //1个层级
                htr.Attributes.Add("data-tt-id", CurrentId.ToString());

                //有父级
                if (CurrentParentMenuTreeId != 0 && CurrentParentMenuTreeId != 0)
                {
                    htr.Attributes.Add("data-tt-parent-id", CurrentParentMenuTreeId.ToString());
                }

                htr.Controls.Add(htc_1);

                hgc.Controls.Add(htr);

                if (isClass)
                {
                    GetMenuTree(CurrentId, ref hgc);
                }

                lay--;//层级减1

            }
        }

        /// <summary>
        /// 是否有子集
        /// </summary>
        /// <param name="cid"></param>
        /// <returns></returns>
        protected static bool GetClassInExist(int cid)
        {
            DataRow[] dr = AppDataCacheServer.MenuTreeList().Select(string.Format("MenuTreeId={0}", cid));

            if (dr != null && dr.Length > 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        #endregion

        protected void InitData(int RoleId)
        {
            rpList = DbHelperSQL.Query(string.Format("select * from vRolePermissions where RoleId={0} and TenantId={1} ", RoleId,CurrentTenantId));

            DataSet ds= DbHelperSQL.Query(string.Format("select * from Permissions where TenantId={0} ", CurrentTenantId));
            dtPermissionsList = ds.Tables[0];
            dtrpList = rpList.Tables[0];
        }

        private void ShowInfo(int Id)
        {
            XinYiOffice.BLL.Roles bll = new XinYiOffice.BLL.Roles();
            XinYiOffice.Model.Roles model = bll.GetModel(Id);

            HiddenField_id.Value = model.Id.ToString();

            this.lblId.Text = model.Id.ToString();
            this.txtName.Text = model.Name;
            this.txtCreateAccountId.Value = model.CreateAccountId.ToString();
            this.txtRefreshAccountId.Value = model.RefreshAccountId.ToString();
            this.txtCreateTime.Value = model.CreateTime.ToString();
            this.txtRefreshTime.Value = model.RefreshTime.ToString();

            InitData(Id);

            InitPermissions(Id);

        }

        /// <summary>
        /// 初始化 权限节点
        /// </summary>
        /// <param name="RoleId"></param>
        public void InitPermissions(int RoleId)
        {

            //菜单权限节点
            for (int i = 0; i < tbody_cell.Controls.Count; i++)
            {
                if (tbody_cell.Controls[i] is System.Web.UI.HtmlControls.HtmlTableRow)
                {
                    if (tbody_cell.Controls[i].Controls[0].Controls[0] is CheckBox)
                    {
                        CheckBox cb = (CheckBox)tbody_cell.Controls[i].Controls[0].Controls[0] as CheckBox;

                        SetCheckBox(ref cb);
                    }
                }
            }

            //具体功能权限节点
            for (int i = 0; i < panPermissions.Controls.Count; i++)
            {
                if (panPermissions.Controls[i] is CheckBox)
                {
                    CheckBox cb = (CheckBox)panPermissions.Controls[i] as CheckBox;

                    SetCheckBox(ref cb);
                }


            }
        }

        /// <summary>
        /// 设置复选框是否具有此权限
        /// </summary>
        /// <param name="cb"></param>
        public void SetCheckBox(ref CheckBox cb)
        {
            if (cb.ToolTip == string.Empty)
            {
                return;
            }

            DataRow[] dr = dtrpList.Select(string.Format("Sign='{0}'", cb.ToolTip));

            if (dr.Length > 0)
            {
                cb.Checked = true;
            }
            else
            {
                cb.Checked = false;
            }
        }

        public void btnCancle_Click(object sender, EventArgs e)
        {
            Response.Redirect("list.aspx");
        }


        protected void LinkButton1_Click(object sender, EventArgs e)
        {
            int Id = int.Parse(this.lblId.Text);
            string Name = this.txtName.Text;
            int CreateAccountId = SafeConvert.ToInt(txtCreateAccountId.Value);
            int RefreshAccountId = SafeConvert.ToInt(txtRefreshAccountId.Value);
            DateTime CreateTime = SafeConvert.ToDateTime(txtCreateTime.Value);
            DateTime RefreshTime = SafeConvert.ToDateTime(txtRefreshTime.Value);

            XinYiOffice.Model.Roles model = new XinYiOffice.Model.Roles();
            model.Id = Id;
            model.Name = Name;
            model.CreateAccountId = CreateAccountId;
            model.RefreshAccountId = RefreshAccountId;
            model.CreateTime = CreateTime;
            model.RefreshTime = RefreshTime;
            model.TenantId = CurrentTenantId;

            XinYiOffice.BLL.Roles bll = new XinYiOffice.BLL.Roles();
            bll.Update(model);

            InitData(Id);

            #region 权限节点保存
            SetPermissionByTr(Id, tbody_cell);
            SetPermissionByPan(Id, panPermissions);
            #endregion

            xytools.web_alert("保存成功！", "list.aspx");
        }

        /// <summary>
        /// 菜单权限
        /// </summary>
        /// <param name="RoleId"></param>
        /// <param name="_pan"></param>
        protected void SetPermissionByTr(int RoleId, Control _pan)
        {
            for (int i = 0; i < _pan.Controls.Count; i++)
            {
                if (_pan.Controls[i] is System.Web.UI.HtmlControls.HtmlTableRow)
                {
                    if (_pan.Controls[i].Controls[0].Controls[0] is CheckBox)
                    {
                        CheckBox cb = (CheckBox)_pan.Controls[i].Controls[0].Controls[0] as CheckBox;
                        if (cb.ToolTip == string.Empty)
                        {
                            continue;
                        }

                        DataRow[] dr = dtrpList.Select(string.Format("Sign='{0}'", cb.ToolTip));

                        if (cb.Checked)
                        {
                            if (dr.Length > 0)
                            {

                            }
                            else
                            {
                                Model.RolePermissions rp = new Model.RolePermissions();
                                rp.CreateAccountId = CurrentAccountId;
                                rp.CreateTime = DateTime.Now;
                                int PermissionId = 0;

                                if (dr == null || dr.Length == 0)
                                {
                                    dr = dtPermissionsList.Select(string.Format("Sign='{0}'", cb.ToolTip));
                                    PermissionId = SafeConvert.ToInt(dr[0]["Id"], -1);
                                }
                                else
                                {
                                    PermissionId = SafeConvert.ToInt(dr[0]["PermissionId"], -1);
                                }

                                rp.PermissionId = PermissionId;
                                rp.RoleId = SafeConvert.ToInt(RoleId);
                                rp.TenantId = CurrentTenantId;

                                new BLL.RolePermissions().Add(rp);
                            }
                        }
                        else
                        {
                            if (dr.Length > 0)
                            {
                                new BLL.RolePermissions().Delete(SafeConvert.ToInt(dr[0]["Id"]));
                            }
                        }

                    }
                }



            }

        }


        /// <summary>
        /// 基本权限
        /// </summary>
        /// <param name="RoleId"></param>
        /// <param name="_pan"></param>
        protected void SetPermissionByPan(int RoleId, Control _pan)
        {
            for (int i = 0; i < _pan.Controls.Count; i++)
            {
                if (_pan.Controls[i] is CheckBox)
                {
                    CheckBox cb = (CheckBox)panPermissions.Controls[i] as CheckBox;
                    if (cb.ToolTip == string.Empty)
                    {
                        continue;
                    }

                    DataRow[] dr = dtrpList.Select(string.Format("Sign='{0}'", cb.ToolTip));

                    if (cb.Checked)
                    {
                        if (dr.Length > 0)
                        {

                        }
                        else
                        {
                            Model.RolePermissions rp = new Model.RolePermissions();
                            rp.CreateAccountId = CurrentAccountId;
                            rp.CreateTime = DateTime.Now;
                            int PermissionId = 0;

                            if (dr == null || dr.Length == 0)
                            {
                                dr = dtPermissionsList.Select(string.Format("Sign='{0}'", cb.ToolTip));
                                PermissionId = SafeConvert.ToInt(dr[0]["Id"], -1);
                            }
                            else
                            {
                                PermissionId = SafeConvert.ToInt(dr[0]["PermissionId"], -1);
                            }

                            rp.PermissionId = PermissionId;
                            rp.RoleId = SafeConvert.ToInt(RoleId);
                            rp.TenantId = CurrentTenantId;

                            new BLL.RolePermissions().Add(rp);
                        }
                    }
                    else
                    {
                        if (dr.Length > 0)
                        {
                            new BLL.RolePermissions().Delete(SafeConvert.ToInt(dr[0]["Id"]));
                        }
                    }

                }


            }




        }
    }
}
